<?php
require_once 'application/library/exception/gcException.php';
require_once 'application/constant/constant.php';
/**
 * fileHelper
 * @author    Soochow University
 * @version   1.0
 * @exclude   作  成  日：2011/04/07
 */
class fileHelper{
    /**
     * 文件存在检查
     * @param    string   $str
     * @return   boolean
     */
    public static function chkFileExist($str){
        if(file_exists($str)){
            return true;
        }else{
            return false;
        }
    }

    /**
     * 解压
     * unZip
     * @param string $zip_filepath
     */
    public static function unZip($zip_filepath,$unZip_filepath) {
        $zip_filepath=iconv("UTF-8", "Shift_JIS", $zip_filepath);
        $unZip_filepath=iconv("UTF-8", "Shift_JIS", $unZip_filepath);
        if(!is_file($zip_filepath)){
            return false;
        }

        $zip = new ZipArchive();
        $rs = $zip->open($zip_filepath);

        if($rs !== true){
            return false;
        }

        $zip->extractTo($unZip_filepath);
        $zip->close();
        return true;
    }
    
    /**
     * 压缩文件
     * zip
     * @param string $zipFilePath
     * @param string $arrFilePath
     */
    public static function zip($zipFilePath,$arrFilePath) {
        $zipFilePath=iconv("UTF-8", "Shift_JIS", $zipFilePath);
        if(empty($arrFilePath)||empty($zipFilePath)){
            return false;
        }
        
        $objZip = new ZipArchive();
        if ($objZip->open($zipFilePath,ZIPARCHIVE::OVERWRITE) === true) { 
            foreach ($arrFilePath as $arrayKey=>$value){
                $value=iconv("UTF-8", "Shift_JIS", $value);
                $file=explode("/",$value);
                $objZip->addFile($value, $file[count($file)-1]); 
            }
            $objZip->close(); 
            return true;
        } else { 
            return false;
        }
    }
    
    /**
     * 压缩
     * @param string $zipFilePath
     */
    public static function getZipObj($zipFilePath){
        $objZip = new ZipArchive();
        if ($objZip->open($zipFilePath,ZIPARCHIVE::OVERWRITE) === true) { 
            return $objZip;
        }else {
            return false;
        }
    }
    /**
     * 取得压缩文件情报
     * getZipInfo
     * @param string $zip_filepath
     */
    public static function getZipInfo($zip_filepath) {
        $zip = zip_open($zip_filepath);
        $zipInfoArray=array();
        $zipInfo = array("name"              =>Character::STRING_BLANK,
                         "actualFilesize"    =>Character::STRING_BLANK,
                         "compressedSize"    =>Character::STRING_BLANK,
                         "compressionMethod" =>Character::STRING_BLANK);
        if ($zip) {
            while ($zip_entry = zip_read($zip)) {
                $zipInfo["name"]              = zip_entry_name($zip_entry);
                $zipInfo["actualFilesize"]    = zip_entry_filesize($zip_entry);
                $zipInfo["compressedSize"]    = zip_entry_compressedsize($zip_entry) ;
                $zipInfo["compressionMethod"] = zip_entry_compressionmethod($zip_entry);
                $zipInfoArray[count($zipInfoArray)]=$zipInfo;
            }
            zip_close($zip);
        }
       return $zipInfoArray;
    }
    
    /**
     * 文件上传
     *@param    string   $ctlName      コントロール名
     *@param    string   $srvPath      サーバで保存パース
     *@param    string   $newFileName  サーバで保存パース
     *@return   array
     */
    public static function upload($ctlName, $srvPath, $newFileName = null,$newFileSuffix=null){
        $arrUploadIf = array( "status" =>"",
                              "name"   =>"",
                              "type"   =>"",
                              "size"   =>"",
                              "messageId"  =>""
                             );
        if(is_dir($srvPath)){
            $errorCode=$_FILES[$ctlName]["error"];
            if ($errorCode > UPLOAD_ERR_OK ) {
                $arrUploadIf["name"]   = $_FILES[$ctlName]["name"];
                $arrUploadIf["type"]   = $_FILES[$ctlName]["type"];
                $arrUploadIf["size"]   = $_FILES[$ctlName]["size"];
                
                if($errorCode == UPLOAD_ERR_PARTIAL){
                    $arrUploadIf["status"] = "1";
                    $arrUploadIf["messageId"] = "ERR-100233";
                }
                
                if($errorCode == UPLOAD_ERR_INI_SIZE ||$errorCode == UPLOAD_ERR_FORM_SIZE) {
                    $arrUploadIf["status"] = "2";
                    $arrUploadIf["messageId"] = "ERR-100266";
                }
                
                if($errorCode == UPLOAD_ERR_NO_FILE ) {
                    $arrUploadIf["status"] = "3";
                    $arrUploadIf["messageId"] = "ERR-100259";
                }
                
                return $arrUploadIf;
            } else {
                if($_FILES[$ctlName]["size"] == 0){
                    $arrUploadIf["status"] = "3";
                    $arrUploadIf["messageId"] = "ERR-100259";
                }else {
                    if(substr($srvPath, -1) != "/"){
                        $srvPath = $srvPath . "/";
                    }
                    if($newFileName){
                        $arrFileName = array();
                        $arrFileName = explode(".",$_FILES[$ctlName]["name"]);
                        if($newFileSuffix){
                            move_uploaded_file($_FILES[$ctlName]["tmp_name"],iconv("UTF-8", "shift-JIS",
                            $srvPath . $newFileName . "." . $newFileSuffix));
                        }else {
                            move_uploaded_file($_FILES[$ctlName]["tmp_name"],iconv("UTF-8", "shift-JIS",
                            $srvPath . $newFileName . "." . $arrFileName[sizeof($arrFileName)-1]));
                        }
                    }else{
                        move_uploaded_file($_FILES[$ctlName]["tmp_name"],iconv("UTF-8", "shift-JIS",
                        $srvPath.$_FILES[$ctlName]["name"]));
                    }

                    $arrUploadIf["status"] = "0";
                    $arrUploadIf["name"]   = $_FILES[$ctlName]["name"];
                    $arrUploadIf["type"]   = $_FILES[$ctlName]["type"];
                    $arrUploadIf["size"]   = $_FILES[$ctlName]["size"];
                    return $arrUploadIf;
                }
            }
        }else{
            throw new gcException();
        }
    }

     /**
     * xml文件读取
     *@param    string   $filePath
     *@param    string   $arrNodeName
     *@return   array
     */
    public static function readXml($filePath,$arrNodeName){
        $filePath = iconv("UTF-8", "Shift_JIS", $filePath);
        if(count($arrNodeName)== 0){
            return;
        }
        $doc = new DOMDocument();
        $doc->load($filePath);
        $arrReadData = array();
        foreach($arrNodeName as $key => $value){
            $arrReadData[$key] = fileHelper::readNode($value,$doc->getElementsByTagName($key));
        }
        unset($doc);
        return $arrReadData;
    }

     /**
     * xml结点读取
     *@param    string   $arrNode
     *@param    string   $Node     
     *@return   array
     */
    private static function readNode($arrNode, $Node){
        if ($arrNode == null || $arrNode == ""){
            $arrResult = array();
            for($i = 0; $i < $Node->length; $i++){
                $nodes = $Node->item($i)->getElementsByTagName("*");
                $arr = array();
                for($ii = 0; $ii < $nodes->length; $ii++){
                    $nodeName = $nodes->item($ii)->nodeName;
                    $nodeId = $nodes->item($ii)->getAttribute('id');
                    $nodeValue = $nodes->item($ii)->nodeValue;
                    $arr[$nodeName][$nodeId] = $nodeValue;
                }
                $arrResult[$Node->item($i)->getAttribute("id")]= $arr;
            }
            return $arrResult;
        }
        foreach($arrNode as $key => $value){
            $arr = array();
            for($i = 0; $i < $Node->length; $i++){
                $objNodes = $Node->item($i)->getElementsByTagName($key);
                $arr[$key] = fileHelper::readNode($arrNode[$key],$objNodes);
            }
            return $arr;
            
        }
    }

     /**
     * xml文件读取
     *@param    string   $filePath
     *@return   object
     */
    public static function readAllXml($filePath){
        if (file_exists($filePath)) {
            return simplexml_load_file($filePath);
        } else {
            return false;
        }
    }

     /**
     * 文件夹复制
     * @param       string  $strFrom
     * @param       string  $strTo
     * @return      bool
     */
    public static function folderCopy($strFrom, $strTo) {
        if (is_dir($strFrom)) {
            if (!file_exists($strTo)) {
                mkdir($strTo);
            } else {}
            if ($intDp = opendir($strFrom)) {
                for ($strFile = readdir($intDp); $strFile; $strFile = readdir($intDp)) {
                    if ($strFile != "." && $strFile != "..") {
                        if (is_dir($strFrom . $strFile)) {
                            if (!fileHelper::folderCopy($strFrom . $strFile . Character::PATH_SEPARATOR,
                                                    $strTo . $strFile . Character::PATH_SEPARATOR)) {
                                return false;
                            } else {}
                        } else {
                            copy($strFrom . $strFile, $strTo . $strFile);
                        }
                    } else {}
                }
            } else {
                //失败
                return false;
            }
            closedir($intDp);
            //成功
            return true;
        } else {
            if (file_exists($strFrom)){
                return copy($strFrom, $strTo);
            }else {
                return false;
            }
        }
    }

     /**
     * 文件夹删除
     * @param       string  $strDir
     * @return      bool
     */
    public static function folderDelete($strDir) {
        if (!file_exists($strDir)){
            return false;
        }
        if (is_dir($strDir)) {
            if ($intDp = opendir($strDir)) {
                for ($strFile = readdir($intDp); $strFile; $strFile = readdir($intDp)) {
                    if ($strFile != "." && $strFile != "..") {
                        $strFullPath = $strDir . Character::PATH_SEPARATOR . $strFile;
                        if (is_dir($strFullPath)) {
                            if (!fileHelper::folderDelete($strFullPath)) {
                                return false;
                            } else {}
                        } else {
                            unlink($strFullPath);
                        }
                    } else {}
                }
            } else {
                return false;
            }
            closedir($intDp);
            if (rmdir($strDir)) {
                return true;
            } else {
                return false;
            }
        } else {
            return unlink($strDir);
        }
    }

    /**
     * 只削除文件夹里面内容
     * @param $strDir
     * @return      bool
     */
    public static function folderClean($strDir) {
        if (!file_exists($strDir)){
            return false;
        }
        if (is_dir($strDir)) {
            if ($intDp = opendir($strDir)) {
                for ($strFile = readdir($intDp); $strFile; $strFile = readdir($intDp)) {
                    if ($strFile != "." && $strFile != "..") {
                        $strFullPath = $strDir . Character::PATH_SEPARATOR . $strFile;
                        if (is_dir($strFullPath)) {
                            if (!fileHelper::folderDelete($strFullPath)) {
                                return false;
                            } else {}
                        } else {
                            unlink($strFullPath);
                        }
                    } else {}
                }
            } else {
                return false;
            }
            closedir($intDp);
        } else {
            return unlink($strDir);
        }
    }
}
